<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/3/12
 * Time: 下午2:08
 */

namespace Biz\module\Classes\mgt;

use Biz\model\activity\GroupBuyGoods as mGroupBuyGoods;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\GoodsExtendInfo as mGoodsExtendInfo;
use Biz\model\GoodsSku;
use Biz\model\GoodsSku as mGoodsSku;
use Biz\model\GoodsSkuAttr as mGoodsSkuAttr;
use Biz\model\OperateLog as mOperateLog;
use Biz\pockets\constInterface\CategoryExtendInfo;
use Biz\service\activity\ActivityRegisterInfo;
use Biz\service\Category as sCategory;
use Biz\service\GoodsInfo;
use Biz\service\GoodsInfo as sGoodsInfo;
use Biz\service\OperateLog as sOperateLog;
use Biz\service\ShopSpecial;
use Doraemon\model\Spu as mSpu;
use Doraemon\model\Videos as mVideos;

final class GoodsSave implements CategoryExtendInfo
{
    const BTN_ID_SAVE_STATUS_ONLINE = 2;//保存并上架
    const BTN_ID_SAVE_STATUS_WAIT_AUDIT = 3;//保存并提交审核

    private static $btnStatus = [
        self::BTN_ID_SAVE_STATUS_ONLINE => mGoodsBasicInfo::STATUS_ONLINE,
        self::BTN_ID_SAVE_STATUS_WAIT_AUDIT => mGoodsBasicInfo::STATUS_WAIT_AUDIT
    ];

    protected function save(&$post, &$goodsInfo, $scenes = 'create', $method = 'insert')
    {

        $result = [];

        $post['scenes'] = $scenes;
        $post['method'] = $method;

        {
            //基本信息结构
            $data = [
                'uid' => $post['uid'],
                'title' => $post['title'],
                'spec_img' => isset($post['images_content'][0]) ? $post['images_content'][0] : '',
            ];

            $result['spec_img'] = $data['spec_img'];

            if ($scenes == 'create') {
                $data['wiki_id'] = isset($post['wiki_id']) ? $post['wiki_id'] : 0;
            }

            //提交的按钮有保存并上线或保存并提交审核时进行状态的变换
            if (isset(self::$btnStatus[$post['btn_id']])) {

                if (isset($post['goods_id'])) {

                    //如果是管理员操作下架的商品，则必须不能进行保存并上架
                    if (mGoodsBasicInfo::checkIsAdminOffline($post['uid'], $post['goods_id'])) {
                        if ($post['btn_id'] == self::BTN_ID_SAVE_STATUS_ONLINE) {
                            $post['btn_id'] = self::BTN_ID_SAVE_STATUS_WAIT_AUDIT;
                        }
                    }
                }

                $data['status'] = self::$btnStatus[$post['btn_id']] ? self::$btnStatus[$post['btn_id']] : mGoodsBasicInfo::STATUS_OFFLINE;

            }

            //根据分类ID获取分类树数组
            if (isset($post['category_id']) && $post['category_id'] > 0) {
                $categories = sCategory::mgtGetSupportTreeInfo($post['uid'], $post['category_id']);
                $categoryId = isset($categories['list'][1]['id']) ? $categories['list'][1]['id'] : 0;
                $secondCategoryId = isset($categories['list'][2]['id']) ? $categories['list'][2]['id'] : 0;
                $thirdCategoryId = isset($categories['list'][3]['id']) ? $categories['list'][3]['id'] : 0;
                $fourCategoryId = isset($categories['list'][4]['id']) ? $categories['list'][4]['id'] : 0;

                $lastCategoryId = $categoryId;
                if ($fourCategoryId) {
                    $lastCategoryId = $fourCategoryId;
                } elseif ($thirdCategoryId) {
                    $lastCategoryId = $thirdCategoryId;
                } elseif ($secondCategoryId) {
                    $lastCategoryId = $secondCategoryId;
                }

                $data = array_merge($data, [
                    'category_id' => $categoryId,
                    'second_category_id' => $secondCategoryId,
                    'third_category_id' => $thirdCategoryId,
                    'four_category_id' => $fourCategoryId,
                    'last_category_id' => $lastCategoryId,
                    'shipping_templ_id' => $post['shipping_templ_id'],
                ]);

                //在扩展信息的材质一步需要使用
                $result['category_id'] = $data['category_id'];
                $result['second_category_id'] = $data['second_category_id'];
                $result['third_category_id'] = $data['third_category_id'];
                $result['four_category_id'] = $data['four_category_id'];
            }

            if (!isset($post['category_id']) || !$post['category_id'] || !isset($secondCategoryId) || !$secondCategoryId) {
                throw new \Exception('请正确填写类目');
            }


            //品牌信息
            if (isset($post['brand_id']) && $post['brand_id'] > 0) {
                $data['brand_id'] = $post['brand_id'];
            }

            $result['goods_id'] = mGoodsBasicInfo::createOrEdit($post['uid'], $post['goods_id'], $data, $post['scenes'], $post['method']);

        }



        {
            // 保存扩展信息之前将视频状态ID置为正常
            $goodsExtenfInfo = mGoodsExtendInfo::getInfo($result['goods_id'], false);
            if (!$post['spec_video']) {
                if ($goodsExtenfInfo['spec_video']) {
                    mVideos::updateStatus($goodsExtenfInfo['spec_video'], mVideos::STATUS_DELETE);
                }
            } else if ($post['spec_video'] && $goodsExtenfInfo['spec_video']) {
                if ($goodsExtenfInfo['spec_video'] != $post['spec_video']) {
                    mVideos::updateStatus($goodsExtenfInfo['spec_video'], mVideos::STATUS_DELETE);
                    mVideos::updateStatus($post['spec_video'], mVideos::STATUS_NORNAL);
                }
            } else {
                mVideos::updateStatus($post['spec_video'], mVideos::STATUS_NORNAL);
            }
        }



        {
            //扩展信息保存
            if ($result['category_id'] == self::CATEGORY_ID_FURNITURE && !$post['material_content']) {
                throw new \Exception('材质为必填项');
            }
//			if ($result['category_id'] == self::CATEGORY_ID_FURNITURE && (!isset(self::CATEGORY_FURNITURE_MOUNT_METION[$post['mounting_method_id']]))) {
//				throw new \Exception('安装方式为必填项');
//			}
            foreach ($post['material_content'] as $k => $materialContent) {
                $post['material_content'][$k] = [
                    'title' => $materialContent['title'],
                    'content' => strip_tags($materialContent['content']),
                ];
            }
            $shippingTime = mGoodsExtendInfo::getShippingTimeOfSave($post['shipping_time_type'], $post['shipping_time']);
            $data = [
                'uid' => $post['uid'],
                'content' => $post['content'],
                'shipping_templ_id' => $post['shipping_templ_id'],
                'shipping_time_type' => $post['shipping_time_type'],
                'shipping_time' => $shippingTime,
                'spec_cover' => $post['spec_cover'],
                'spec_video' => $post['spec_video'],
                'images_content' => json_encode($post['images_content']),
                'style_content' => $post['style_content'],
                'material_content' => $post['material_content'],
                'inspection_report' => $post['inspection_report'],
                'is_bywiki' => (isset($post['wiki_id']) && !empty($post['wiki_id'])) ? 1 : 0,
                //家具类 商品 安装方式 字段
                'mounting_method' => $result['category_id'] == self::CATEGORY_ID_FURNITURE && isset(self::CATEGORY_FURNITURE_MOUNT_METION[$post['mounting_method_id']]) ?
                    $post['mounting_method_id']
                    :
                    0
            ];

            if (isset($result['second_category_id'])) {
                $data['second_category_id'] = $result['second_category_id'];
            }

            if (!empty($goodsInfo)) {
                $data['second_category_id'] = $goodsInfo['second_category_id'];
            }

            $second_category_id = $data['second_category_id'];

            mGoodsExtendInfo::createOrEdit($post['uid'], $result['goods_id'], $data, $post['scenes'], $post['method']);

        }



        {
            $ExtendInfoTempl = sCategory::mgtGetCategoryInfoTempl($second_category_id)['size'];
            $ExtendInfoTempl = array_combine(
                array_column($ExtendInfoTempl, 'key'),
                array_column($ExtendInfoTempl, 'unit')
            );


            //商品SKU信息保存
            if (isset($post['sku_attr']) && !empty($post['sku_attr'])) {
                //sku信息格式化并保存
                foreach ($post['sku_attr'] as $attr) {

                    if (is_array($attr)) {
                        $data = [];

                        if (!isset($attr['t1_title']) && !isset($attr['t2_title'])) {
                            throw new \Exception('请填写属性');
                        }

                        if (empty($attr['t1_title']) && empty($attr['t2_title'])) {
                            throw new \Exception('请填写属性');
                        }


                        //skuattr保存
                        if (isset($attr['t1_title']) && !empty($attr['t1_title'])) {
                            $data[mGoodsSkuAttr::$typeDesc[mGoodsSkuAttr::TYPE_T1]] = [
                                'type' => mGoodsSkuAttr::TYPE_T1,
                                'title' => $attr['t1_title'],
                                'value' => $attr['t1_value'],
                                'extend_info' => $attr['extend_info'],
                                'status' => mGoodsSkuAttr::STATUS_PASSED
                            ];
                        }
                        if (isset($attr['t2_title']) && !empty($attr['t2_title'])) {
                            $data[mGoodsSkuAttr::$typeDesc[mGoodsSkuAttr::TYPE_T2]] = [
                                'type' => mGoodsSkuAttr::TYPE_T2,
                                'title' => $attr['t2_title'],
                                'value' => $attr['t2_value'],
                                'status' => mGoodsSkuAttr::STATUS_PASSED
                            ];
                        }

                        foreach ($data as $tKey => $tRow) {
                            $result['attrIds'][$tKey] = mGoodsSkuAttr::createOrEdit($post['uid'], $result['goods_id'], $tRow, $post['scenes']);
                        }
                    }

                    if ($attr['extinfo']) {
                        $extendInfos = array_intersect_key($attr['extinfo'], $ExtendInfoTempl);
                    }

                    if ($extendInfos) {
                        array_walk($extendInfos, function (&$value, $key) use ($ExtendInfoTempl) {
                            $value = str_replace([$ExtendInfoTempl[$key], ' ', 'cm'], '', $value) . " " . $ExtendInfoTempl[$key];
                        });
                    }

                    //sku 信息保存
                    $data = [
                        'uid' => $post['uid'],
                        'goods_id' => $result['goods_id'],
                        'title' => $post['title'],
                        'sku_attr_t1' => isset($result['attrIds']['t1']) ? $result['attrIds']['t1'] : 0,
                        'sku_attr_t2' => isset($result['attrIds']['t2']) ? $result['attrIds']['t2'] : 0,
                        'price' => $attr['price'],
                        'weight' => isset($attr['weight']) ? $attr['weight'] : 0,
                        'sku_no' => isset($attr['sku_no']) ? $attr['sku_no'] : '',
                        'volume' => isset($attr['volume']) ? $attr['volume'] : 0.00,
                        'forecast_ship_time' => isset($attr['forecast_ship_time']) ? $attr['forecast_ship_time'] : "0000-00-00",
                        'extinfo' => json_encode($extendInfos, JSON_UNESCAPED_UNICODE),
                        'status' => mGoodsSkuAttr::STATUS_PASSED,
                        'shipping_templ_id' => $post['shipping_templ_id']//用于判断weigth是否需要传
                    ];

                    if (!is_null($attr['stock'])) {
                        $data['stock'] = $attr['stock'];
                    }

                    //sku 保存
                    $sku_id = mGoodsSku::createOrEdit($post['uid'], $result['goods_id'], $data, $post['scenes']);

                    $priceLogData[] = [
                        'sku_id' => $sku_id,
                        'sku_name' => $attr['t1_value'] . " " . $attr['t2_value'],
                        'price' => $attr['price'],
                    ];

                    $skuIds[] = $sku_id;
                }

                //添加sku价格变动日志
                ($result['goods_id'] && isset($priceLogData)) ? GoodsInfo::admAddPriceLog($result['goods_id'], $priceLogData) : null;

                if ($post['goods_id'] > 0) {

                    mGoodsSku::delNotInSkuIds($post['uid'], $post['goods_id'], $skuIds);


                }


            } else {
                throw new \Exception('请正确填写商品属性信息');
            }
        }

        {

            //最后执行的任务
            $prices = array_column($post['sku_attr'], 'price');
            $stock = array_sum(array_column($post['sku_attr'], 'stock'));

            $result['max_min_price'] = $data = [
                'min_price' => min($prices),
                'max_price' => max($prices),
                'stock' => $stock
            ];

            mGoodsBasicInfo::createOrEdit($post['uid'], $result['goods_id'], $data, null, 'update');

            return $result;
        }

    }

    public function saveSku($shopId, $goodsId, $skuInfo)
    {
        return mGoodsSku::saveSkuInfo($shopId, $goodsId, $skuInfo);
    }

    public function saveShippingTime($goodsIds, $shipingType, $shippingTime)
    {
        $shippingTime = mGoodsExtendInfo::getShippingTimeOfSave($shipingType, $shippingTime);
        return mGoodsExtendInfo::multiSaveShippingTime($goodsIds, $shipingType, $shippingTime);
    }


    public function create(&$post)
    {

        //wiki如果提供，则查询其分类id和品牌id并使用
        if (isset($post['wiki_id'])) {
            if ($post['wiki_id'] > 0) {
                $wiki = mSpu::getFieldById($post['wiki_id'], ['brand_id', 'category_id', 'third_category_id']);

                if (!empty($wiki)) {
                    $post['category_id'] = $wiki['third_category_id'] > 0 ? $wiki['third_category_id'] : $wiki['category_id'];
                    $post['brand_id'] = $wiki['brand_id'];

                }
            }
        }


        $result = $this->save($post, $goodsInfo, 'create', 'insert');

        $lastCategory_id = $result['category_id'];
        if ($result['four_category_id']) {
            $lastCategory_id = $result['four_category_id'];
        } else if ($result['third_category_id']) {
            $lastCategory_id = $result['third_category_id'];
        } else if ($result['second_category_id']) {
            $lastCategory_id = $result['second_category_id'];
        }
        {
            $wikiData = [
                'wiki_id' => $post['wiki_id'],
                'title' => $post['title'],
                'goods_id' => $result['goods_id'],
                'brand_id' => $post['brand_id'],
                'category_id' => $result['category_id'],
                'last_category_id' => $lastCategory_id,
                'spec_img' => $result['spec_img'],
                'images_content' => json_encode($post['images_content']),
                'style_content' => $post['style_content'],
                'min_price' => $result['max_min_price']['min_price'],
                'max_price' => $result['max_min_price']['max_price'],
                'material_content' => $post['material_content'],
                'extinfo' => array_map(function ($v) {
                    return $v['extinfo'];
                }, $post['sku_attr'])
            ];

            sGoodsInfo::createOrSyncWiki($wikiData);
        }

        return $result;

    }

    private function is_can_update($goodsBasicInfo, $skuAttr)
    {
        $registerTags = ActivityRegisterInfo::getRegisterInfos([$goodsBasicInfo['goods_id']]);
        $specialRegisterTags = ShopSpecial::getRegisterSpecialInfos([$goodsBasicInfo['goods_id']]);
        $skuInfo = GoodsSku::getSkuInfo([$goodsBasicInfo['goods_id']], true, false);
        $skuInfoGrpId = array_column($skuInfo[$goodsBasicInfo['goods_id']]['list'], null, 'sku_id');

        $is_change_sku = array_diff(array_column($skuInfo[$goodsBasicInfo['goods_id']]['list'], 'sku_id'), array_column($skuAttr, 'sku_id'));

        if ($registerTags && isset($registerTags[$goodsBasicInfo['goods_id']])) {
            if ($is_change_sku) {
                throw new \Exception('已经报名参加了平台活动「' . $registerTags[$goodsBasicInfo['goods_id']][0] . '」，请先从活动里移除之后再添加');
            }
            foreach ($skuAttr as $sku) {
                if (!isset($sku['sku_id'])) {
                    throw new \Exception('参加活动的商品， 请取消报名之后再操作');
                }
                if ($specialRegisterTags && isset($specialRegisterTags[$goodsBasicInfo['goods_id']])) {
                    if ($skuInfoGrpId[$sku['sku_id']]['price'] != $sku['price']) {
                        throw new \Exception('不得更改sku价格' . $skuInfoGrpId[$sku['sku_id']]['price'] . "_" . $sku['price']);
                    }
                } else {
                    if ($registerTags[$goodsBasicInfo['goods_id']][$sku['sku_id']]['actual_price'] > $sku['price']) {
                        throw new \Exception('不得低于参加活动的价格');
                    }
                }
            }

        }

        $HasNotOverGroupBuy = mGroupBuyGoods::getNotOverInfos($goodsBasicInfo['goods_id']);
        if ($HasNotOverGroupBuy) {
            foreach ($skuAttr as $item) {
                if (!isset($item['sku_id'])) {
                    throw new \Exception('参加团购的商品不允许增加sku');
                }
            }
        }


    }

    public function update(&$post)
    {
        //当编辑状态的时候不可传wikiID
        unset($post['wiki_id']);

        $goodsInfo = mGoodsBasicInfo::getInfo($post['goods_id'], ['goods_id', 'uid', 'title', 'second_category_id']);
        $this->is_can_update($goodsInfo, $post['sku_attr']);

        if ($goodsInfo['uid'] != $post['uid']) {
            throw new \Exception('抱歉，此商品不存在');
        }

        $result = $this->save($post, $goodsInfo, 'update', 'update');


        //商品保存之后的操作

        {
            //如果修改了商品标题、修改了商品图片，则需要进行报警
            $check1 = $post['title'] != $goodsInfo['title'];

            //加上标题和图片是否修改的判断
            $extendInfo = mGoodsExtendInfo::getInfo($result['goods_id'], false);


            $check2 = $extendInfo['images_content'] != json_encode($post['images_content']);

            if ($check1 || $check2) {
                sOperateLog::record(mOperateLog::TYPE_GOODS_ALARM, $post['uid'], $result['goods_id'], [
                    'title' => $goodsInfo['title'],
                    'images' => $extendInfo['images_content']
                ], [
                    'title' => $post['title'],
                    'images' => $post['images_content']
                ]);
            }
        }

        return $result;


    }
}